const cloud = require('wx-server-sdk')
cloud.init()

exports.main = async (event) => {
  const db = cloud.database()
  const wxContext = cloud.getWXContext()
  
  try {
    // 获取当前用户所有打卡记录（按时间倒序）
    const res = await db.collection('checkInRecords')
      .where({
        openid: wxContext.OPENID
      })
      .orderBy('createTime', 'desc')
      .get()

    // 转换UTC时间格式
    const records = res.data.map(item => ({
      id: item._id,
      date: formatUTCDate(item.createTime),
      time: item.time
    }))

    return {
      success: true,
      data: records
    }
  } catch (err) {
    return {
      success: false,
      message: err.message
    }
  }
}

// UTC日期格式化 (YYYY/MM/DD)
function formatUTCDate(timestamp) {
  const date = new Date(timestamp)
  return `${date.getUTCFullYear()}/${date.getUTCMonth()+1}/${date.getUTCDate()}`
}

// UTC时间格式化 (HH:MM)
function formatUTCTime(timestamp) {
  const date = new Date(timestamp)
  return `${date.getUTCHours()}:${date.getUTCMinutes()}`
}